//
//  UIButton+extension.swift
//  WeiboClassSix
//
//  Created by HM on 16/10/6.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

extension UIButton {
    
    //1. 对于使用最广泛的参数值,可以设成默认值
    //2. 对于可以设为nil的参数,要设成可选值
    //3. 要保证至少一个参数,没有默认值,不然会和 self.init()冲突
    
    /// UIButton的便利构造器
    convenience init (title: String?, titleColor: UIColor = UIColor.darkGray, fontSize: CGFloat = 15, image: String? = nil, backgroundImage: String? = nil, target: AnyObject? = nil, action: Selector? = nil ,event: UIControlEvents = .touchUpInside) {
        self.init()
        
        //设置文字
        if let title = title {
            self.setTitle(title, for: .normal)
            self.setTitle(title, for: .highlighted)
            self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
        }
        
        //设置图片
        if let image = image {
            let image = UIImage(named: image)
            let highlightedImage = UIImage(named: "\(image)_highlighted")
            self.setImage(image, for: .normal)
            self.setImage(highlightedImage, for: .highlighted)
        }
        
        //设置背景图片
        if let backgroundImage =  backgroundImage {
            let bgimage = UIImage(named: backgroundImage)
            let bghighlightedImage = UIImage(named: "\(backgroundImage)_highlighted")
            self.setBackgroundImage(bgimage, for: .normal)
            self.setBackgroundImage(bghighlightedImage, for: .highlighted)
        }
        
        //添加事件
        if let target = target, let action = action {
            self.addTarget(target, action: action, for: event)
        }
        
        //自适应大小
        self.sizeToFit()
    }
}
